"""K8s资源Markdown写入器工厂模块"""

from typing import Dict, Type
import logging
from src.writers.base import Writer

class WriterFactory:
    """
    写入器工厂类
    负责创建对应资源类型的Markdown写入器
    """
    
    # 存储已注册的写入器类
    _writers: Dict[str, Type[Writer]] = {}
    
    # 记录器
    _logger = logging.getLogger(__name__)
    
    @classmethod
    def register(cls, resource_type: str, writer_class: Type[Writer]) -> None:
        """
        注册写入器类
        
        Args:
            resource_type: 资源类型名称，如 'Deployment', 'Service'
            writer_class: 对应的写入器类
        """
        cls._writers[resource_type] = writer_class
        cls._logger.debug(f"注册写入器: {resource_type} -> {writer_class.__name__}")
    
    @classmethod
    def create_writer(cls, resource_type: str, config_manager=None, logger=None) -> Writer:
        """
        创建指定类型的写入器实例
        
        Args:
            resource_type: 资源类型名称
            config_manager: 配置管理器实例
            logger: 日志记录器实例
            
        Returns:
            对应类型的写入器实例
            
        Raises:
            ValueError: 当不支持该资源类型时
        """
        if resource_type not in cls._writers:
            cls._logger.warning(f"未找到{resource_type}类型的写入器，尝试动态导入")
            cls._try_import_writer(resource_type)
        
        writer_class = cls._writers.get(resource_type)
        if not writer_class:
            raise ValueError(f"不支持的资源类型: {resource_type}")
        
        cls._logger.debug(f"创建{resource_type}写入器实例")
        return writer_class(config_manager=config_manager, logger=logger)
    
    @classmethod
    def _try_import_writer(cls, resource_type: str) -> None:
        """尝试动态导入写入器类"""
        try:
            # 尝试动态导入
            # 转换为小写模块名，例如 Deployment -> deployment
            module_name = resource_type.lower()
            module_path = f"src.writers.{module_name}"
            
            import importlib
            module = importlib.import_module(module_path)
            
            # 假设模块中的写入器类名为 资源类型名 + "Writer"
            writer_class_name = f"{resource_type}Writer"
            if hasattr(module, writer_class_name):
                writer_class = getattr(module, writer_class_name)
                cls.register(resource_type, writer_class)
                cls._logger.info(f"成功动态导入写入器: {resource_type}")
            else:
                cls._logger.error(f"找不到写入器类: {writer_class_name}")
        except (ImportError, AttributeError) as e:
            cls._logger.error(f"导入{resource_type}写入器失败: {str(e)}")
    
    @classmethod
    def get_supported_types(cls) -> list:
        """
        获取所有支持的资源类型
        
        Returns:
            支持的资源类型列表
        """
        return list(cls._writers.keys())
    
    @classmethod
    def is_supported(cls, resource_type: str) -> bool:
        """
        检查是否支持指定的资源类型
        
        Args:
            resource_type: 资源类型名称
            
        Returns:
            是否支持该类型
        """
        if resource_type not in cls._writers:
            cls._try_import_writer(resource_type)
        return resource_type in cls._writers


# 以下代码为示例，注册内置写入器
# 在实际开发时，可以在各写入器模块中导入工厂并注册
# 或者在应用启动时统一注册

# 示例自动注册机制
def register_built_in_writers() -> None:
    """注册内置写入器"""
    # 核心工作负载资源
    try:
        from src.writers.deployment import DeploymentWriter
        WriterFactory.register('Deployment', DeploymentWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.statefulset import StatefulSetWriter
        WriterFactory.register('StatefulSet', StatefulSetWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.daemonset import DaemonSetWriter
        WriterFactory.register('DaemonSet', DaemonSetWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.job import JobWriter
        WriterFactory.register('Job', JobWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.cronjob import CronJobWriter
        WriterFactory.register('CronJob', CronJobWriter)
    except ImportError:
        pass
    
    # 服务发现与负载均衡资源
    try:
        from src.writers.service import ServiceWriter
        WriterFactory.register('Service', ServiceWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.ingress import IngressWriter
        WriterFactory.register('Ingress', IngressWriter)
    except ImportError:
        pass
    
    # 配置与存储资源
    try:
        from src.writers.configmap import ConfigMapWriter
        WriterFactory.register('ConfigMap', ConfigMapWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.secret import SecretWriter
        WriterFactory.register('Secret', SecretWriter)
    except ImportError:
        pass
    
    try:
        from src.writers.persistentvolumeclaim import PersistentVolumeClaimWriter
        WriterFactory.register('PersistentVolumeClaim', PersistentVolumeClaimWriter)
    except ImportError:
        pass

# 注册内置写入器
register_built_in_writers()
